import os
from typing import Any
import pandas as pd
import pandas_xlwt # не убирать!
from MyLogger import MyLogger
from MyConfig import MyConfig
from MainConsolidator import MainConsolidator
from OraWorker import OraWorker
import sys
###########################
from handlers2.strips_t2 import handler
###########################

check:bool = True
module:str = handler.module_name()
cur_path = os.path.dirname(os.path.realpath(__file__))
conf = f"{cur_path}\\consolidation.json"
logger = MyLogger(name="debug",log_file="debug_single.log",outStream=sys.stdout,mode="w")
cfg = MyConfig(conf)
hlist:list = cfg.get("handlers",None)
# hdict:dict = cfg.get("level2 handlers",None)
hdict={}
for item in hlist:
    hdict[item["key"]]=item["module"]
h = handler()
cc = h.get_compiled()

ora = OraWorker("manage_dw","ufyjwhb","172.17.80.116/scpora",".\\ora")

def handler_cc(rec:pd.Series,consolidator:MainConsolidator)->pd.Series:
    try:
        result:pd.Series={"f1":0}
        module_name=f"__{hdict[rec['Производство2']]}__"
        logger.info(f"module {module_name}")
        namespace={"consolidator":consolidator , "record":rec, "result":result,"__name__":module_name}
        exec(cc,namespace)
        return namespace["result"]
    except Exception as exp: 
        logger.error("handler2 error",exc_info=True)

def check_handler(rec:pd.Series)->pd.Series:
    check = ora.product_check(str(rec["Продукт УП"]),str(rec["ID в SAP ERP VMZ"]))
    # rec["exists"] = ora.product_exists(str(rec["Продукт УП"]))
    # rec["ok"]=rec["Продукт УП"]==rec["Название продукта УП"]
    rec["ID в SAP ERP VMZ"]=str(rec["ID в SAP ERP VMZ"])
    rec["Есть в УП"] = check[1]
    rec["Уже укрупнено"] = check[2]
    rec["Уже укрупнено в"] = check[0]
    print(check)
    return rec

if __name__=="__main__":
    try:
        df = pd.read_excel(f"{cur_path}\\output\\input_data.xlsx",sheet_name="Sheet1")
        logger.info("input data loaded")
        consolidator = MainConsolidator(f"{cur_path}\\debug_single.log",logStream=sys.stdout)
        consolidator.load_guids_x(".\\guids")
        cols=df.columns.to_list() #+["Продукт УП","error","Время укрупнения"]
        df1 = h.debug_handle(df[df["Производство2"]==module],consolidator,module)
        logger.info("handler applied")
        df1[cols].to_excel(f"{cur_path}\\output\\single_debug.xlsx",index=False)
        # df1[cols].to_excel(f"{cur_path}\\output\\single_debug2.xls",index=False,engine="xlwt")
        # df2=df[df["Производство2"]==module].apply(lambda row: handler_cc(row,consolidator),axis=1)
        # df2[cols].to_excel(f"{cur_path}\\output\\single_debug_cc.xlsx",index=False) 
        # logger.info("cc handler applied")

        if check:
            # check_df = pd.read_excel(f"{cur_path}\\misc\\check_SAP.xlsx")[["Код продукта SAP","Полное название продукта SAP","Название продукта УП"]]
            # logger.info("check data loaded")
            # df3= df1[["ID в SAP ERP VMZ","Продукт УП"]]
            # df_checked = df3.merge(check_df,how="left",left_on="ID в SAP ERP VMZ",right_on="Код продукта SAP")
            # df_checked = df_checked.apply(check_handler,axis=1)
            df3= df1[["ID в SAP ERP VMZ","Полное наименование материала","Вид материала в SAP ERP","Продукт УП"]]
            df_checked = df3.apply(check_handler,axis=1)
            df_checked.to_excel(f"{cur_path}\\output\\checked.xls",index=False,engine="xlwt")
            logger.info("checked")
            ora.close()
    except:
        logger.error("error",exc_info=True)








